
package galaxy.app.route;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import galaxy.app.Galaxy;
import galaxy.app.log.LogHelper;
import galaxy.app.network.rpc.packet.RequestPacket;
import galaxy.app.network.rpc.packet.ResponsePacket;
import galaxy.app.network.rpc.packet.RpcCallbackPacket;
import galaxy.app.network.session.NettySession;
import galaxy.kernel.utils.StringUtils;

/**
 * 处理Client信息并相应
 */
public abstract class DefaultClientRoute implements BaseRoute<RequestPacket> {
    // static final Logger LOGGER = LoggerFactory.getLogger(DefaultProtobufHandlerRoute.class);
    // static Logger RPC_LOGGER = LoggerFactory.getLogger("rpc");

    RouteSystem route ;

    public DefaultClientRoute(){
        route = Galaxy.systems().get(RouteSystem.class);
    }

    @Override
    public long getThreadHash(NettySession session, RequestPacket packet) {
        return packet.uid;
    }

    @Override
    public void onReceive(NettySession session, RequestPacket packet) {
        try {
            RouteInfo routeInfo = route.getRouteInfo(packet.route);
            if (routeInfo.method.isVoid()) {
                routeInfo.invoke(packet.args);
                return;
            }

            // RpcCallbackPacket rsp = new RpcCallbackPacket();
            // rsp.sequenceId = packet.sequenceId;
            // rsp.result = routeInfo.invoke(packet.args);
            // session.writeRpcPacket(rsp);
            Object result = routeInfo.invoke(packet.args);

            ResponsePacket rsp = new ResponsePacket();
            rsp.uid = packet.uid;
            rsp.messageId = packet.messageId;
            rsp.route = packet.route;
            rsp.data =  ((String)result).getBytes();
            session.writeAndFlush(rsp);

        } catch (Exception ex) {
            LogHelper.error("", ex);
        } finally {
            // if (LogHelper.isInfoEnabled()) {
                long durationTime = System.currentTimeMillis() - packet.buildTime;
                if (durationTime > 50) {
                    LogHelper.warn("<---------- [rpc]client -> invoke complete. duration time:{}ms ---------->", durationTime);
                    LogHelper.warn("packet = {}", packet);
                    LogHelper.warn("<---------- [rpc]client -> invoke complete. duration time:{}ms ---------->", durationTime);
                }
            // }
        }
    }
}
